package com.huanghwh.sync.message.service.impl;


import cn.hutool.http.HttpUtil;
import com.huanghwh.sync.message.service.IMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;

/**
 * @Author: huanghwh
 * @Date: 2021/10/2 上午12:45
 */
@Slf4j
@Service
public class MessageServiceImpl implements IMessageService {


    @Value("${message.barkUrl}")
    private String barkUrls;


    /**
     * 向Bark-App推送消息
     *
     * @param msg
     * @author huanghwh
     * @date 2021/10/2 上午12:46
     */
    @Async
    @Override
    public void sendMessageToBark(String msg) {
        if (StringUtils.isEmpty(msg)) {
            throw new RuntimeException("推送消息至Bark失败：msg为空");
        }
        if (StringUtils.isEmpty(barkUrls)) {
            throw new RuntimeException("推送消息至Bark失败：barkUrls为空");
        }
        try {
            String[] barkUrlArray = barkUrls.split(",");
            for (String barkUrl : barkUrlArray) {
                // 处理url
                String url = MessageFormat.format(barkUrl, msg);
                HttpUtil.get(url);
            }
            log.info("推送消息至Bark成功: {}", msg);
        } catch (Exception e) {
            log.error("推送消息至Bark失败：" + e);
            throw e;
        }
    }


}
